<template>
	<view>
		<!-- #ifdef APP-PLUS -->
		<view>
			<uni-nav-bar :border="false" :fixed="true" :statusBar="true">
				<view slot="left" class="index-title">
					<image :src="commonImg('dingwei.png')" class="index-title-icon"></image>
					<text class="index-title-txt">{{ address }}</text>
					<image :src="commonImg('downarrow.png')" class="index-title-addressicon"></image>
				</view>
			</uni-nav-bar>
		</view>
		<!-- #endif -->
		<view class="index">
			<!-- #ifdef H5 || MP -->
			<view class="index-title">
				<image :src="commonImg('dingwei.png')" class="index-title-icon"></image>
				<text class="index-title-txt">{{ address }}</text>
				<image :src="commonImg('downarrow.png')" class="index-title-addressicon"></image>
			</view>
			<!-- #endif -->
			<view @click="onClickGotoSearchPage" class="index-input">
				<view class="index-input-wrap">
					<image :src="commonImg('search.png')" class="index-input-wrap-icon"></image>
					<text class="index-input-wrap-txt">搜搜你喜欢的店</text>
				</view>
			</view>
			<view class="index-swiper">
				<view class="index-swiper-content">
					<swiper :indicator-color="indicatorColor" :indicator-active-color="indicatorActiveColor" :indicator-dots="true"
					 autoplay circular>
						<block v-for="item of swiperData" :key="item.id">
							<swiper-item>
								<image mode="aspectFill" :src="commonImg(item.image_url)" class="index-swiper-content-item-img"></image>
							</swiper-item>
						</block>
					</swiper>
				</view>
			</view>
			<view class="index-swipernav">
				<view class="index-swipernav-content">
					<swiper :indicator-color="indicatorNavColor" :indicator-active-color="indicatorActiveNavColor" :indicator-dots="true"
					 :autoplay="false">
						<swiper-item v-for="(page, index) of pages" :key="index">
							<view class="index-swipernav-content-item">
								<view @click="onClickGotoSearchResult(item)" class="index-swipernav-content-item-itemdetail" v-for="item of page"
								 :key="item.id">
									<image :src="commonImg(item.imageUrl)" class="index-swipernav-content-item-itemdetail-img"></image>
									<text class="index-swipernav-content-item-itemdetail-txt">{{ item.name }}</text>
								</view>
							</view>
						</swiper-item>
					</swiper>
				</view>
			</view>
			<view class="index-banner">
				<block v-for="item of adData" :key="item.id">
					<image mode="aspectFill" class="index-banner-img" :src="commonImg(item.image_url)"></image>
				</block>
			</view>
			<view class="index-select">
				<!-- <view @click="onClickSelectIndex(0)" :class="{ 'index-select-item-active': selectIndex === 0 }" class="index-select-item">综合排序</view> -->
				<!-- <view @click="onClickSelectIndex(1)" :class="{ 'index-select-item-active': selectIndex === 1 }" class="index-select-item">评分排序</view> -->
				<!-- <view @click="onClickSelectIndex(2)" :class="{ 'index-select-item-active': selectIndex === 2 }" class="index-select-item">距离排序</view> -->
				<view :class="{ 'index-select-item-active': selectIndex === 2 }" class="index-select-item">距离排序</view>
			</view>
			<view class="index-list">
				<commodityList :stores="store_list"></commodityList>
			</view>
			<view class="index-btn savepadding">
				<button @click="onClickscanCode" class="index-btn-btn">
					<image :src="commonImg('saoma.png')" class="index-btn-btn-img"></image>
					<text class="index-btn-btn-txt">扫码结账</text>
				</button>
			</view>
		</view>
	</view>
</template>
<script>
	import commodityList from "@/components/commodity-list/list.vue"
	import {
		config,
		myGetDistance
	} from '@/utils/config.js';
	import {
		myMixin
	} from '@/utils/mixin.js';
	import uniNavBar from '@/components/uni-nav-bar/uni-nav-bar.vue';
	// #ifdef H5
	const jweixin = require('../../utils/jweixin-module.js');
	// #endif
	export default {
		mixins: [myMixin],
		components: {
			uniNavBar,
			commodityList
		},
		computed: {
			pages() {
				const pages = [];
				this.navData.forEach((item, index) => {
					const page = Math.floor(index / 5);
					if (!pages[page]) {
						pages[page] = [];
					}
					pages[page].push(item);
				});
				return pages;
			}
		},
		onReachBottom() {
			const page1 = this.zh_page + 1;
			const totalPage = this.zh_totalPage
			if (page1 <= totalPage) {
				this.zh_page = page1
				this._getShopData()
			} else {
				uni.showToast({
					title: '已经到底部了',
					icon: 'none'
				})
			}
		},
		onPullDownRefresh() {
			this.store_list = []
			this.zh_page = 1
			this.zh_size = 10
			this.zh_total = 0
			this.zh_totalPage = 0
			this._getShopData()
		},
		data() {
			return {
				indicatorColor: '#fff',
				indicatorActiveColor: '#FD4D7D',
				indicatorNavColor: '#D8D8D8',
				indicatorActiveNavColor: '#F02230',
				selectIndex: 2,
				adData: [],
				swiperData: [],
				navData: [],
				store_list: [],
				zh_page: 1,
				zh_size: 10,
				zh_total: 0,
				zh_totalPage: 0,
				latitude: '', // 你自己的纬度
				longitude: '', // 你自己的经度
				address: '正在获取您的地址',
				h5ListHeight: 0,
				appListHeight: 0,
			};
		},
		onLoad() {
			// #ifdef APP-PLUS || MP
			// 获取你自己的经纬度
			uni.getLocation({
				type: 'wgs84',
				success: res => {
					this.latitude = res.latitude;
					this.longitude = res.longitude;
					this._getShopData(); // 综合的商家
				},
				fail: err => {
					this.latitude = undefined;
					this.longitude = undefined;
				},
				complete: () => {
					this._beginSetAddress(); // 开始设置地址的信息
				}
			});
			// #endif
			// #ifdef H5
			// h5版本的获取摄像头
			this._beginSetAddressByH5()
			// #endif
			this._getBannerData(); // 轮播图
		},
		onReady() {
			const that = this
			uni.getSystemInfo({
				success: ((res) => {
					let info = uni.createSelectorQuery().select(".index-select");
					info.boundingClientRect(function(data) {
						that.h5ListHeight = res.windowHeight - data.height - 44 // 小程序和H5是可以这么设置，但是到了自定义头部的时候，是不允许这么设置的
						that.appListHeight = res.windowHeight - res.statusBarHeight - 44 - data.height // app的height
					}).exec()
				})
			})
		},
		methods: {
			// 获取经纬度和位置
			_beginSetAddress() {
				const longitude = this.longitude;
				const latitude = this.latitude;
				if (!longitude) {
					return false
				}
				if (!latitude) {
					return false
				}
				uni.request({
					url: `${config.api_base_url}member/map/getAddress/${longitude}/${latitude}/`,
					success: res => {
						let {
							status,
							data
						} = res.data;
						if (status.flag === true) {
							this.address = `${data.addressComponent.district}`;
						} else {
							this.address = '';
						}
					},
					fail: () => {
						this.address = '';
					},
					complete: (() => {
						this._getShopData(); // 综合的商家
					})
				});
			},
			pageTotal(rowCount, pageSize) {
				if (rowCount === null || rowCount === "") {
					return 0;
				} else {
					if ((pageSize !== 0) && (rowCount % pageSize === 0)) {
						return parseInt(rowCount / pageSize)
					}
					if ((pageSize !== 0) && (rowCount % pageSize !== 0)) {
						return parseInt(rowCount / pageSize) + 1
					}
				}
			},
			_beginSetAddressByH5() {
				uni.request({
					url: `${config.api_base_url}orders/pay/config`,
					method: 'POST',
					data: {
						url: window.location.href.split('#')[0]
					},
					success: ((res) => {
						let {
							status,
							data
						} = res.data
						if (status.flag === true) {
							jweixin.config({
								debug: false,
								appId: data.appid,
								timestamp: data.timestamp,
								nonceStr: data.nonceStr,
								signature: data.signature,
								jsApiList: ['getLocation', 'scanQRCode']
							});
							jweixin.ready(() => {
								jweixin.getLocation({
									type: 'wgs84',
									success: ((res) => {
										this.latitude = res.latitude;
										this.longitude = res.longitude;
										this._beginSetAddress(); // 开始设置地址的信息
									}),
									fail: (() => {
										this.latitude = undefined;
										this.longitude = undefined;
									})
								})
							})
							jweixin.error((err) => {
								console.log(JSON.stringify(err))
							})
						}
					})
				})
			},
			// 判断公众号截取code
			getUrlParam(name) {
				let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
				let r = window.location.search.substr(1).match(reg);
				if (r != null) {
					return unescape(r[2]);
				}
				return null;
			},
			onClickGotoSearchResult(item) {
				const id = item.id
				const name = item.name
				if (!id) {
					return false
				}
				uni.navigateTo({
					url: `../searchresult/searchresult?flag=1&id=${id}&name=${name}`
				})
			},
			onClickscanCode() {
				// #ifdef H5
				if ((!uni.getStorageSync('openId')) && (!this.getUrlParam('code'))) {
					let url = window.location.href
					let new_url = encodeURIComponent(url)
					window.location.href =
						`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx6246e0503023027f&redirect_uri=${new_url}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`
				} else if ((!uni.getStorageSync('openId')) && (this.getUrlParam('code'))) {
					uni.showLoading({
						title: '正在启动摄像头'
					})
					const token = uni.getStorageSync('token')
					const code = this.getUrlParam('code')
					uni.request({
						url: `${config.api_base_url}member/member/openid/${code}`,
						header: {
							'Content-Type': 'application/json'
						},
						success: ((res) => {
							let {
								status,
								data
							} = res.data
							if (status.flag === true) {

								// this._setUserAvatar(data) // 设置用户头像

								uni.setStorageSync('openId', data.openid)
								if (!token) {
									uni.request({
										url: `${config.api_base_url}member/member/login/openId`,
										data: {
											openId: data.openid
										},
										method: 'POST',
										success: ((res_n) => {
											let {
												status,
												data
											} = res_n.data
											if (status.flag === true) {
												uni.setStorageSync('role', data.role)
												uni.setStorageSync('token', data.token)
												uni.setStorageSync('memberId', data.memberId)
												this._openWXSM()
											}
										})
									})
								} else {
									this._openWXSM()
								}
							}
						})
					})
				} else if (uni.getStorageSync('openId')) {
					uni.showLoading({
						title: '正在启动摄像头'
					})
					const token = uni.getStorageSync('token')
					if (!token) {
						uni.request({
							url: `${config.api_base_url}member/member/login/openId`,
							data: {
								openId: uni.getStorageSync('openId')
							},
							method: 'POST',
							success: ((res_n) => {
								let {
									status,
									data
								} = res_n.data
								if (status.flag === true) {
									uni.setStorageSync('role', data.role)
									uni.setStorageSync('token', data.token)
									uni.setStorageSync('memberId', data.memberId)
									this._openWXSM()
								}
							})
						})
					} else {
						this._openWXSM()
					}
				}
				// #endif
				// #ifndef H5
				const token = uni.getStorageSync('token')
				if (!token) {
					uni.showToast({
						icon: 'none',
						title: '尚未登录, 请先登录'
					})
					setTimeout(() => {
						uni.removeStorageSync('role')
						uni.removeStorageSync('memberId')
						uni.removeStorageSync('token')
						uni.removeStorageSync('openId')
						uni.reLaunch({
							url: '../verificationcodelogin/verificationcodelogin'
						})
					}, 777)
					return false
				}
				uni.scanCode({
					success: ((res) => {
						let url = res.result
						let newUrl = url.split('#')[1]
						uni.navigateTo({
							url: newUrl
						})
					})
				})
				// #endif
			},
			// 打开微信扫码
			_openWXSM() {
				uni.hideLoading()
				jweixin.scanQRCode({
					needResult: 1,
					desc: 'scanQRCode desc',
					success: ((res) => {
						let url = res.resultStr
						let newUrl = url.split('#')[1]
						uni.navigateTo({
							url: newUrl
						})
					})
				})
			},
			_getAdData() {
				uni.request({
					url: `${config.api_base_url}ad/ad/index`,
					method: 'POST',
					data: {
						area_list:this.address
					},
					success: res => {
						let {
							status,
							data
						} = res.data;
						if (status.flag === true) {
							this.adData = data;
						} else {
							this.adData = [];
						}
					},
					fail: () => {
						this.adData = [];
					},
					complete: () => {}
				});
			},
			_getBannerData() {
				uni.showLoading({
					title: '加载中'
				})
				uni.request({
					url: `${config.api_base_url}ad/banner/index`,
					method: 'POST',
					data: {
						area_list:this.address
					},
					success: res => {
						let {
							status,
							data
						} = res.data;
						if (status.flag === true) {
							this.swiperData = data;
						} else {
							this.swiperData = [];
						}
					},
					fail: () => {
						this.swiperData = [];
					},
					complete: (() => {
						this._getNavData(); // nav数据
					})
				});
			},
			_getNavData() {
				uni.request({
					url: `${config.api_base_url}merchant/industry/index`,
					success: res => {
						let {
							status,
							data
						} = res.data;
						if (status.flag === true) {
							this.navData = data;
						} else {
							this.navData = [];
						}
					},
					complete: (() => {
						this._getAdData(); // 广告
					})
				});
			},
			_getShopData() {
				let zh_page = this.zh_page;
				let zh_size = this.zh_size;
				uni.request({
					url: `${config.api_base_url}merchant/store/getStoresByPoint/${zh_page}/${zh_size}`,
					method: 'POST',
					header: {
						'Content-Type': 'application/json'
					},
					data: {
						latitude:this.latitude,
						longitude:this.longitude,

					},
					success: res => {
						let {
							status,
							data
						} = res.data;
						if (status.flag === true) {
							for (const item of data.storeAndTagsList) {
								if (item.store.latitude && item.store.latitude) {
									const result = myGetDistance(this.latitude, this.longitude, item.store.latitude, item.store.longitude);
									if (result) {
										item.store.jlresult = result;
									}
								}
								if (item.store.rate) {
									const vip2 = JSON.parse(item.store.rate).vip2;
									item.store.vip2 = Math.floor(vip2 * 100) / 10;
									const vip1 = JSON.parse(item.store.rate).vip1;
									item.store.vip1 = Math.floor(vip1 * 100) / 10;
								}
							}
							this.zh_total = data.total;
							this.zh_totalPage = this.pageTotal(this.zh_total, this.zh_size)

							// 获取到距离排序列表数据
							this.store_list = this.store_list.concat(data.storeAndTagsList);
							// forEach循环遍历数组，拿到距离的值,定义一个空的数组保存排序之后的数据
							// var new_store_list=[]
							// 对距离的值使用sort方法进行倒叙排序
							// this.store_list.forEach((item,index)=>{
								// var newList=item.store.jlresult;
							// })
							// 然后把排序后的数据给空的数组
						} else {
							this.zh_total = 0;
							this.zh_totalPage = 0;
							this.store_list = [];
						}
					},
					fail: () => {
						this.store_list = [];
						this.zh_total = 0;
						this.zh_totalPage = 0;
					},
					complete: (() => {
						uni.hideLoading()
						uni.stopPullDownRefresh()
					})
				});
			},
			onClickSelectIndex(index) {
				this.selectIndex = index;
			},
			onClickGotoSearchPage() {
				uni.navigateTo({
					url: '../search/search'
				});
			},
			onClickGotoShopDetailPage(id) {
				if (!id) {
					return false;
				}
				uni.navigateTo({
					url: `../shopdetail/shopdetail?id=${id}`
				});
			},

		}
	};
</script>
<style>
	page {
		background-color: #fff;
	}
</style>
<style scoped>
	/* ios底部安全距离-padding */
	.savepadding {
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		box-sizing: content-box;
	}

	.index {
		width: 100%;
	}

	.index-title {
		width: 100%;
		height: 44px;
		line-height: 44px;
		display: flex;
		align-items: center;
		box-sizing: border-box;
		padding-left: 34rpx;
		position: fixed;
		background-color: #fff;
		z-index: 1;
	}

	.index-title-icon {
		width: 26rpx;
		height: 32rpx;
		margin-right: 16rpx;
	}

	.index-title-txt {
		font-size: 30rpx;
		font-weight: 400;
		line-height: 42rpx;
		margin-right: 12rpx;
		color: #636363;
	}

	.index-title-addressicon {
		width: 16rpx;
		height: 10rpx;
	}

	.index-input {
		width: 100%;
		/* #ifdef APP-PLUS */
		height: 64rpx;
		/* #endif */
		/* #ifdef H5 || MP */
		height: 152rpx;
		padding-top: 44px;
		/* #endif */
		display: flex;
		align-items: center;
		box-sizing: border-box;
		padding-left: 30rpx;
		padding-right: 30rpx;
	}

	.index-input-wrap {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #f8f8f8;
		border-radius: 8rpx;
	}

	.index-input-wrap-icon {
		width: 34rpx;
		height: 34rpx;
		margin-right: 8rpx;
	}

	.index-input-wrap-txt {
		font-size: 28rpx;
		color: #676767;
		line-height: 28rpx;
		font-weight: 400;
	}

	.index-swiper {
		width: 100%;
		height: 270rpx;
		margin-top: 12rpx;
		box-sizing: border-box;
		padding-left: 30rpx;
		padding-right: 30rpx;
	}

	.index-swiper-content {
		width: 100%;
		height: 270rpx;
	}

	.index-swiper-content uni-swiper {
		height: 270rpx;
	}

	.index-swiper-content swiper {
		height: 270rpx;
	}

	.index-swiper-content-item-img {
		width: 100%;
		height: 270rpx;
		background-color: #eee;
		border-radius: 20rpx;
	}

	.index-swiper-content uni-swiper>>>.uni-swiper-dots-horizontal {
		right: 5%;
		left: auto;
		bottom: 20rpx;
		display: flex;
		align-items: center;
	}

	.index-swiper-content uni-swiper>>>.uni-swiper-dot {
		width: 4rpx;
		height: 4rpx;
	}

	.index-swiper-content uni-swiper>>>.uni-swiper-dot-active {
		width: 12rpx;
		height: 12rpx;
	}

	.index-swipernav {
		width: 100%;
		margin-top: 14rpx;
		box-sizing: border-box;
		padding-left: 44rpx;
		padding-right: 44rpx;
	}

	.index-swipernav-content {
		width: 100%;
		height: 184rpx;
	}

	.index-swipernav-content uni-swiper {
		height: 184rpx;
	}

	.index-swipernav-content swiper {
		height: 184rpx;
	}

	.index-swipernav-content-item {
		width: 100%;
		height: 100%;
		display: flex;
	}

	.index-swipernav-content-item-itemdetail {
		width: 20%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.index-swipernav-content-item-itemdetail-img {
		width: 94rpx;
		height: 94rpx;
		border-radius: 50%;
		margin-bottom: 16rpx;
	}

	.index-swipernav-content-item-itemdetail-txt {
		font-size: 24rpx;
		font-weight: 400;
		line-height: 32rpx;
		color: #333333;
	}

	.index-swipernav-content uni-swiper>>>.uni-swiper-dot {
		width: 14rpx;
		height: 8rpx;
		border-radius: 4rpx;
	}

	.index-swipernav-content uni-swiper>>>.uni-swiper-dot-active {
		width: 28rpx;
		height: 8rpx;
		border-radius: 4rpx;
	}

	.index-banner {
		width: 100%;
		height: 188rpx;
		box-sizing: border-box;
		padding-left: 44rpx;
		padding-right: 44rpx;
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
	}

	.index-banner-img {
		width: 322rpx;
		height: 168rpx;
	}

	.index-select {
		width: 100%;
		height: 72rpx;
		box-sizing: border-box;
		/* prod */
		/* padding-left: 116rpx; */
		/* prod */

		/* temp */
		padding-left: 16rpx;
		/* temp */

		padding-right: 116rpx;
		display: flex;
		align-items: center;
	}

	.index-select-item {
		width: 33.33%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		font-weight: 600;
		color: #242424;
		line-height: 72rpx;
	}

	.index-select-item-active {
		color: #fd4d7d;
		position: relative;
	}

	.index-select-item-active::after {
		content: ' ';
		position: absolute;
		width: 60rpx;
		height: 4rpx;
		background-color: #f02230;
		border-radius: 2rpx;
		left: 50%;
		bottom: 0;
		margin-left: -30rpx;
	}

	.index-list {
		width: 100%;
		box-sizing: border-box;
		padding-top: 16rpx;
		padding-left: 16rpx;
		padding-right: 14rpx;
		background-color: #faf7fa;
	}






	.index-btn {
		position: fixed;
		left: 50%;
		/* #ifdef APP-PLUS || MP */
		bottom: 7px;
		/* #endif */
		/* #ifdef H5 */
		bottom: 57px;
		/* #endif */
		margin-left: -213rpx;
		width: 426rpx;
		height: 76rpx;
		border-radius: 38rpx;
		line-height: 76rpx;
	}

	.index-btn-btn {
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #f02230;
		border-radius: 38rpx;
	}

	.index-btn-btn-img {
		width: 48rpx;
		height: 48rpx;
		margin-right: 18rpx;
	}

	.index-btn-btn-txt {
		font-weight: 500;
		font-size: 28rpx;
		color: #fff;
	}
</style>
